var express = require('express');
var router = express.Router();
var User = require('../util/bean/users')
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
})
router.post('/login',function (req,res,next) {

    console.log("jinlaile")
    let acc = req.body.account;
    let pass = req.body.password;

    //console.log(req.body)
    let user = new User({
        account:acc,
        password:pass,
    })
    user.findByAccount(acc).then(function (data) {
        if(data&&data.password===pass){
          res.cookie('account',acc);
          res.cookie('password',pass);
          res.cookie('_id',data._id);
          // req.session.account = acc;
          res.render("index");
          // res.json(data);
        }else {
          res.json({error:1})
        }
    })
})

//跳转到注册页面
router.get("/toRegister",function (req,res) {
    res.render("view/register");
    console.log("here i am again");
});

//注册
router.post('/register',function (req,res,next) {
    let obj = {
        account:req.body.account,
        nikeName: req.body.nikeName,
        password: req.body.password,
        friend : []
    }
    let user = new User(obj);
    user.findByAccount(user.account).then(function (data) {
        if(data){
            res.json({error:'duplicated account'});
        }else{
            user.save(user).then(function (data) {
                // 如果成功则保存当前用户信息并renderindex页面
                // req.session.account = obj.account;
                res.cookie('account',obj.account);
                res.cookie('password',obj.password);
                res.cookie('_id',data._id);
                res.render("index");
            }).catch(function (err) {
                res.json({error:err.message});
            })
        }
    });

})

//好友列表
router.get('/getMyFriend',function (req,res) {
    let userid = req.cookies._id;
    if(userid){
        let user = new User({_id:userid});
        user.findById(user).then(function (data) {
            let friendList = [];
            let friendId = data.friend;
            try {
                let promiseList = [];
                friendId.forEach(function (element) {

                    let promise = new Promise(function (resolve,reject) {
                        //console.log('element:',element);
                        user.findById({_id:element}).then(function (data) {
                            //console.log('data:',data);
                            resolve(data)
                        })
                    })
                    promiseList.push(promise);
                })
                Promise.all(promiseList).then(function (datas) {
                    res.json(datas);
                })
            }catch(e){
                res.json({error:e.message});
            }
        })
    }else {
        res.json({result:'未登录'});
    }

})

//用户模糊查询
router.get('/findUsers',function (req,res) {
    let nikeName = req.param('nikeName');
    let user = new User({});
    user.findByNikeName(nikeName).then(function (data) {
        res.json(data);
    })
})
//添加好友
router.get('/addFriend',function (req,res) {
    let masterid = req.cookies._id;
    //console.log(masterid);
    let id = req.param('id');
    // if(masterid == id)
    // {
    //     res.json({result:"can't add yourself as a friend"});
    // }
    let user = new User({_id:masterid});
    user.findById(user).then(function (data) {
        let friends = data.friend;
        let duplicate = false;
        friends.forEach(function (e) {
            if(e === id){
                duplicate = true;
            }
        })
        if(duplicate){
            res.json({result:'existed friend'});
        }else {
            user.addFriend(data, id).then(function (_) {
                res.json({result: 'success'});
            }).catch(function (data) {
                res.json({result:data})
            })
        }
    })

})
router.get('/findById',function (req,res) {
    let userid = req.param('userid');
    let user = new User({_id:userid});
    user.findById(user).then(function (data) {
        res.json(data);
    })
})
module.exports = router;
